<template>
  <div class="document-page">
    <CommonNavigateBar />
    <div class="document-page__content">
      <div class="document-page__content-search">
        <CommonSearch />
      </div>
      <div class="document-page__content-panel">
        <div class="document-list">
          <div class="document-list__header">
            <DocumentMenu v-model="menuActive" :options="categoryOptions" />
          </div>
          <div
            :class="[menuIndex === 0 && 'first-active']"
            class="document-list__content"
          >
            <div class="document-list__content-nav">
              <CommonNav
                v-model="subMenuActive"
                :options="subMenuOptions"
                :need-right="true"
                :collapse="isCollapse"
              >
                <template #right>
                  <div class="collapse-btn" @tap="onCollapseChange">
                    <span
                      :class="[isCollapse && 'collapse-btn__label-close']"
                      class="collapse-btn__label"
                    >
                      {{ isCollapse ? "关闭" : "全部" }}
                    </span>
                    <image
                      v-show="!isCollapse"
                      src="@/assets/document/arrow-down.png"
                      class="collapse-btn__icon"
                    />
                  </div>
                </template>
              </CommonNav>
              <div class="document-list__content-nav_panel">
                <DocumentNavPanel
                  v-model="subMenuActive"
                  v-model:visible="isCollapse"
                  :options="subMenuOptions"
                />
              </div>
            </div>

            <div class="document-list__content-list">
              <div
                v-show="isCollapse"
                class="document-list__content-list_overlay"
                @tap="onCollapseChange"
              ></div>
              <CommonScroll
                :onPullup="onPullup"
                :onPulldown="onPulldown"
                :pulldown-enabled="false"
              >
                <DocumentItem
                  v-for="(item, index) in articleList"
                  :key="index"
                  :data="item"
                  @tap="onSelect(item.id)"
                />
              </CommonScroll>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
// import CommonPage from "@/components/common-page/index.vue";
import CommonScroll from "@/components/common-scroll/index.vue";
import CommonNavigateBar from "@/components/common-navigateBar/index.vue";
import CommonSearch from "@/components/common-search/index.vue";
import DocumentMenu from "./components/document-menu.vue";
import CommonNav from "@/components/common-nav/index.vue";
import DocumentItem from "./components/document-item.vue";
import DocumentNavPanel from "./components/document-nav-panel.vue";

import { apiQueryArtickeById, apiQueryArticleCategory } from "@/apis/knowledge";

// import isEqual from "lodash.isequal";

import "./index.less";
import { computed, ref, watch } from "vue";
import Taro, { useDidHide, useDidShow } from "@tarojs/taro";
import { ResponseCodeEnum } from "@/constants/index";
import { CommonScrollProps } from "@/components/common-scroll/index.vue";
import { IPage } from "@/apis/types";
import { DUCUMENT_CATEGORY_ID } from "@/constants/index";
import { IArticalCategoryItem } from "@/apis/types/knowledge";
import { useTabBarSelected } from "@/hooks/useTabBarSelected";

defineOptions({
  name: "document-page",
});
const { setSelectIndex } = useTabBarSelected();
const defaultSubMenuActive = ref<number | null>(null);
const menuActive = ref<number | null>(null);
const subMenuActive = ref<number | null>(null);
const isCollapse = ref(false);
const categoryOptions = ref<IArticalCategoryItem[]>([]);
const articleList = ref<any[]>([]);
const page = ref<IPage>({ page: 1, pageSize: 20 });
const loadMore = ref(true);

const menuIndex = computed(() => {
  return categoryOptions.value.findIndex(
    (item: any) => item.id === menuActive.value
  );
});

const subMenuOptions = computed(() => {
  const temp: any = categoryOptions.value.find(
    (item: any) => item.id === menuActive.value
  );
  return temp ? temp.children : [];
});

useDidShow(() => {
  setSelectIndex(1);
  const categoryId = Taro.getStorageSync(DUCUMENT_CATEGORY_ID);
  if (categoryId) {
    // 反向设置
    defaultSubMenuActive.value = categoryId;
    Taro.removeStorageSync(DUCUMENT_CATEGORY_ID);
  }
  queryArticleCategoryServer();
});

useDidHide(() => {
  defaultSubMenuActive.value = null;
  menuActive.value = null;
  subMenuActive.value = null;
  isCollapse.value = false;
  categoryOptions.value = [];
  articleList.value = [];
  page.value = { page: 1, pageSize: 20 };
  loadMore.value = true;
});

const onPullup: CommonScrollProps["onPullup"] = async (done) => {
  try {
    if (!subMenuActive.value) return;

    page.value.page++;
    await queryArticleByIdServer(subMenuActive.value);
  } catch (error) {
    console.log(error);
  } finally {
    done();
  }
};

const onPulldown: CommonScrollProps["onPulldown"] = (done) => {
  done();
};

watch(
  () => subMenuOptions.value,
  (val) => {
    if (!val || !val.length) return;
    if (defaultSubMenuActive.value) {
      subMenuActive.value = defaultSubMenuActive.value;
      // 消费完了就要置空
      defaultSubMenuActive.value = null;
    } else {
      subMenuActive.value = val[0].id;
    }
  },
  { immediate: true, deep: true }
);

watch(
  () => subMenuActive.value,
  (val) => {
    if (val === null) return;
    page.value.page = 1;
    articleList.value = [];

    queryArticleByIdServer(val);
  }
);

const onCollapseChange = () => {
  isCollapse.value = !isCollapse.value;
};

const onSelect = (id: number) => {
  Taro.navigateTo({
    url: `/packageA/pages/knowledge-detail/index?id=${id}`,
  });
};

const findParentId = (
  data: IArticalCategoryItem[],
  sourceId: number
): number | null => {
  let mainId: number | null = null;
  for (let i = 0; i < data.length; i++) {
    const mainItem = data[i];
    for (let j = 0; j < mainItem.children.length; j++) {
      const child = mainItem.children[j];
      if (child.id === sourceId) {
        mainId = mainItem.id;
        break;
      }
    }
  }

  return mainId;
};
const queryArticleCategoryServer = () => {
  apiQueryArticleCategory().then((res) => {
    categoryOptions.value = res.data;
    if (defaultSubMenuActive.value) {
      const mainId = findParentId(res.data, defaultSubMenuActive.value);
      if (mainId) {
        menuActive.value = mainId;
        return;
      }
    }
    menuActive.value = (categoryOptions.value[0] as any).id;
  });
};

const queryArticleByIdServer = (id: number) => {
  apiQueryArtickeById(id, page.value).then((res: any) => {
    const { code, data } = res;
    if (code === ResponseCodeEnum.SUCCESS) {
      const { items, meta } = data;
      articleList.value = articleList.value.concat(items);

      const { totalPages } = meta;
      loadMore.value = page.value.page < totalPages;
    }
  });
};
</script>
